﻿//-----------------------------------------------------------------------------------
// Detailed Extraction Rule Template version 1.0
//-----------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.Xml;
using System.Xml.XPath;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
namespace WebServicesTesting.Automation.WebTest.ExtractionRules 
{
    [System.ComponentModel.DisplayName("ParameterExtraction")]
    [System.ComponentModel.Description("TODO: Add a more detailed description of ParameterExtraction extraction rule.")]
    public class ParameterExtraction : ExtractionRule
    {
        #region Constructors
        /// <summary>
        /// standard constructor
        /// </summary>
        public ParameterExtraction() { }
        #endregion

        #region Properties
        /// <summary>
        /// If True, the extraction rule fails if not found.
        /// </summary>
        
       
        [System.ComponentModel.Description("If True, the extraction rule fails if not found.")]
        [System.ComponentModel.DefaultValue(true)]
        private string xPathExpression;
        public string XPathExpression
        {
            get { return xPathExpression; }
            set { xPathExpression = value; }
        }

        string contextParam;

        public string ContextParam
        {
            get { return contextParam; }
            set { contextParam = value; }
        }
        /*
         * Public properties on the class will be surfaced to the user in the VS UI.
         * Only string, int, and bool types are allowed.
         */

        /*
            /// <summary>
            /// Sample string property
            /// </summary>
            private string m_myStringProperty;
            [System.ComponentModel.DisplayName("My String Property")]
            [System.ComponentModel.Description("Enter a long description for this property.")]
            [System.ComponentModel.DefaultValue("MyString")]
            public string MyStringProperty
            {
                get { return m_myStringProperty; }
                set { m_myStringProperty = value; }
            }
        */

        #endregion // Properties

        #region Utility Functions
        /// <summary>
        /// A sample utility function that performs the actual work of extracting values. 
        /// This demonstrates the best practice of moving most of the code out into 
        /// it's own function so you can test it from a unit test.
        /// </summary>
        /// <returns>true - value found, false - value not found, reason contains more details</returns>
        public bool Extract(string document)
        {
            Debug.Assert(document != null);
            // TODO:  Implement your extraction code here
            throw (new NotImplementedException("ExtractionRule1:MyExtractionFunction not implemented !"));

            // m_extractedValue = "Value found";
            // m_message = "Additional information regarding success/failure of function";
            // return true; // true if found, false if not found
        }
        #endregion

        #region Extract Method
        /// <summary>
        /// The Extract method.  The parameter e contains the Web test context.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void Extract(object sender, ExtractionEventArgs e)
        {
           
              try
            {
                var doc = (StringHttpBody)e.Request.Body;
                string body= doc.BodyString;
                XmlDocument resXmldoc = new XmlDocument();
                resXmldoc.LoadXml(body);

                XmlNamespaceManager nsMgr = new XmlNamespaceManager(resXmldoc.NameTable);
                nsMgr.AddNamespace("s", resXmldoc.DocumentElement.NamespaceURI);
                XPathNavigator nav = resXmldoc.CreateNavigator();
                XmlNode responseBody = resXmldoc.SelectSingleNode("//s:Body", nsMgr);
                string text = null;
                while (responseBody.HasChildNodes)
                {
                    text = responseBody.Name;
                    if (text == xPathExpression)
                    {
                        break;
                    }
                    else
                    {
                        responseBody = responseBody.LastChild;
                    }
                }
                
                int count = responseBody.ChildNodes.Count;
                string nodeName= "";
                string[] nodeValue = new string[count];
                XmlNodeList node = responseBody.ChildNodes;
                e.WebTest.Context["Parameter Count"] = count;
                for(int i=0;i<count;i++)
                {
                    nodeName =nodeName+ node[i].Name +" - " +node[i].InnerText.ToString()+ ", ";
                   
                }
                
                nodeName = nodeName.Substring(0, (nodeName.Length - 2));

                e.WebTest.Context[ContextParam] = nodeName;

                //SqlConnection mySqlConnection = new SqlConnection("Data Source=(local);Initial Catalog=Sample_App;Integrated Security=True");

                //SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
                //mySqlCommand.CommandText = "Select * from Sample_App where Roll_Number=IDENT_CURRENT('Sample_App')";

                //mySqlConnection.Open();
                //SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader(CommandBehavior.SingleRow);

                //while (mySqlDataReader.Read())
                //{
                //    string a= mySqlDataReader[0].ToString();
                //    string b = mySqlDataReader[4].ToString();
                //}


        

            }
            
            catch (Exception ex)
            {
                e.Message = String.Format(CultureInfo.CurrentCulture, "{0}[{1}] Exception: {2}", "ExtractionRule1", this.ContextParameterName, ex.Message.ToString());
                e.Success = false;
            }
           
        }
        #endregion
    }
}
